import type { CompanyInfo, DictItem, EmployeeInfo, OwnerFreightPageRequest, OwnerFreightPageResponse, PaymentTypeDict, TenantDepartTree, UserListResponse } from '@/api/types/system'
import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import {
  getBpmTaskStatusDict,
  getDepartUserList,
  getInvoiceTypeDict,
  getLogisticsFreightTypeDict,
  getLogisticsPayTypeDict,
  getPaymentTypeDict,
  getSysOwnerFreightPage,
  getUserTenantDepartTree,
  queryAllEmployee,
  queryCompanyNew,
} from '@/api/system'

/**
 * 系统通用数据状态管理
 */
export const useSystemStore = defineStore(
  'system',
  () => {
    // 部门树数据
    const tenantDepartTree = ref<TenantDepartTree | null>(null)

    // 支付方式字典
    const logisticsPayTypeDict = ref<DictItem[]>([])

    // 付款方式字典
    const paymentTypeDict = ref<PaymentTypeDict[]>([])

    // 发票类型字典
    const invoiceTypeDict = ref<DictItem[]>([])

    // 运输类型字典
    const logisticsFreightTypeDict = ref<DictItem[]>([])

    // 审批状态字典
    const bpmTaskStatusDict = ref<DictItem[]>([])

    // 公司信息列表
    const companyList = ref<CompanyInfo[]>([])

    // 员工信息列表
    const employeeList = ref<EmployeeInfo[]>([])

    // 部门下用户列表 - 始终保证为数组格式
    const departUserList = ref<UserListResponse[]>([])

    // 运输方式分页数据
    const ownerFreightPage = ref<OwnerFreightPageResponse | null>(null)

    // 加载状态
    const loading = ref<Record<string, boolean>>({})

    // 错误信息
    const error = ref<Record<string, string>>({})

    // 计算属性：获取默认公司
    const defaultCompany = computed(() => {
      return companyList.value.length > 0 ? companyList.value[0] : null
    })

    // 计算属性：根据ID查找公司
    const getCompanyById = computed(() => (id: string) => {
      return companyList.value.find(company => company.id === id) || null
    })

    // 计算属性：根据ID查找员工
    const getEmployeeById = computed(() => (id: string) => {
      return employeeList.value.find(employee => employee.id === id) || null
    })

    // 计算属性：获取简便信息
    const getSelectUserList = computed(() => () => {
      // 确保 departUserList.value 是数组
      if (!Array.isArray(departUserList.value)) {
        console.warn('departUserList.value 不是数组，当前值:', departUserList.value)
        return []
      }

      // 返回用户特定字段
      return departUserList.value
        .filter(user => user.status === 0)
        .map(user => ({
          id: user.id,
          username: user.username,
          realname: user.realname,
          phone: user.phone,
          departIds: user.departIds,
          departNames: user.departNames,
          managerUser: user.managerUser,
        }))
        .flat()
        // 按姓名排序a-z
        .sort((a, b) => a.realname.localeCompare(b.realname))
    })

    /**
     * 获取机构部门树
     */
    async function fetchUserTenantDepartTree(forceRefresh = false) {
      // 如果已有数据且不强制刷新，则直接返回
      if (tenantDepartTree.value && !forceRefresh) {
        return tenantDepartTree.value
      }

      try {
        loading.value.tenantDepartTree = true
        error.value.tenantDepartTree = ''
        const res = await getUserTenantDepartTree()
        tenantDepartTree.value = res.data || null
        return res
      }
      catch (err: any) {
        error.value.tenantDepartTree = err.message || '获取部门树失败'
        throw err
      }
      finally {
        loading.value.tenantDepartTree = false
      }
    }

    /**
     * 获取支付方式字典
     */
    async function fetchLogisticsPayTypeDict(forceRefresh = false) {
      // 如果已有数据且不强制刷新，则直接返回
      if (logisticsPayTypeDict.value.length > 0 && !forceRefresh) {
        return logisticsPayTypeDict.value
      }

      try {
        loading.value.logisticsPayTypeDict = true
        error.value.logisticsPayTypeDict = ''
        const res = await getLogisticsPayTypeDict()
        logisticsPayTypeDict.value = res.data || null
        return res
      }
      catch (err: any) {
        error.value.logisticsPayTypeDict = err.message || '获取支付方式失败'
        throw err
      }
      finally {
        loading.value.logisticsPayTypeDict = false
      }
    }

    /**
     * 获取付款方式字典
     */
    async function fetchPaymentTypeDict(forceRefresh = false) {
      // 如果已有数据且不强制刷新，则直接返回
      if (paymentTypeDict.value.length > 0 && !forceRefresh) {
        return paymentTypeDict.value
      }

      try {
        loading.value.paymentTypeDict = true
        error.value.paymentTypeDict = ''
        const res = await getPaymentTypeDict()
        paymentTypeDict.value = res.data || null
        return res
      }
      catch (err: any) {
        error.value.paymentTypeDict = err.message || '获取付款方式失败'
        throw err
      }
      finally {
        loading.value.paymentTypeDict = false
      }
    }

    /**
     * 获取发票类型字典
     */
    async function fetchInvoiceTypeDict(forceRefresh = false) {
      // 如果已有数据且不强制刷新，则直接返回
      if (invoiceTypeDict.value.length > 0 && !forceRefresh) {
        return invoiceTypeDict.value
      }

      try {
        loading.value.invoiceTypeDict = true
        error.value.invoiceTypeDict = ''
        const res = await getInvoiceTypeDict()
        invoiceTypeDict.value = res.data || null
        return res
      }
      catch (err: any) {
        error.value.invoiceTypeDict = err.message || '获取发票类型失败'
        throw err
      }
      finally {
        loading.value.invoiceTypeDict = false
      }
    }

    /**
     * 获取运输类型字典
     */
    async function fetchLogisticsFreightTypeDict(forceRefresh = false) {
      // 如果已有数据且不强制刷新，则直接返回
      if (logisticsFreightTypeDict.value.length > 0 && !forceRefresh) {
        return logisticsFreightTypeDict.value
      }

      try {
        loading.value.logisticsFreightTypeDict = true
        error.value.logisticsFreightTypeDict = ''
        const res = await getLogisticsFreightTypeDict()
        logisticsFreightTypeDict.value = res.data || null
        return res
      }
      catch (err: any) {
        error.value.logisticsFreightTypeDict = err.message || '获取运输类型失败'
        throw err
      }
      finally {
        loading.value.logisticsFreightTypeDict = false
      }
    }

    /**
     * 获取审批状态字典
     */
    async function fetchBpmTaskStatusDict(forceRefresh = false) {
      // 如果已有数据且不强制刷新，则直接返回
      if (bpmTaskStatusDict.value.length > 0 && !forceRefresh) {
        return bpmTaskStatusDict.value
      }

      try {
        loading.value.bpmTaskStatusDict = true
        error.value.bpmTaskStatusDict = ''
        const res = await getBpmTaskStatusDict()
        bpmTaskStatusDict.value = res.data || null
        return res
      }
      catch (err: any) {
        error.value.bpmTaskStatusDict = err.message || '获取审批状态失败'
        throw err
      }
      finally {
        loading.value.bpmTaskStatusDict = false
      }
    }

    /**
     * 获取公司信息列表
     */
    async function fetchCompanyList(forceRefresh = false) {
      // 如果已有数据且不强制刷新，则直接返回
      if (companyList.value.length > 0 && !forceRefresh) {
        return companyList.value
      }

      try {
        loading.value.companyList = true
        error.value.companyList = ''
        const res = await queryCompanyNew()
        companyList.value = res.data || null
        return res
      }
      catch (err: any) {
        error.value.companyList = err.message || '获取公司信息失败'
        throw err
      }
      finally {
        loading.value.companyList = false
      }
    }

    /**
     * 获取员工列表
     */
    async function fetchEmployeeList(params?: Record<string, any>, forceRefresh = false) {
      // 如果已有数据且不强制刷新，则直接返回
      if (employeeList.value.length > 0 && !forceRefresh && !params) {
        return employeeList.value
      }

      try {
        loading.value.employeeList = true
        error.value.employeeList = ''
        const res = await queryAllEmployee(params)
        // 如果有参数，合并结果；否则直接替换
        if (params) {
          employeeList.value = [...employeeList.value, ...(res.data || [])]
        }
        else {
          employeeList.value = res.data || []
        }
        return res
      }
      catch (err: any) {
        error.value.employeeList = err.message || '获取员工列表失败'
        throw err
      }
      finally {
        loading.value.employeeList = false
      }
    }

    /**
     * 获取运输方式分页数据
     */
    async function fetchOwnerFreightPage(data: OwnerFreightPageRequest, forceRefresh = false) {
      // 如果已有数据且不强制刷新，则直接返回
      if (ownerFreightPage.value && !forceRefresh) {
        return ownerFreightPage.value
      }

      try {
        loading.value.ownerFreightPage = true
        error.value.ownerFreightPage = ''
        const res = await getSysOwnerFreightPage(data)
        ownerFreightPage.value = res.data || null
        return res
      }
      catch (err: any) {
        error.value.ownerFreightPage = err.message || '获取运输方式失败'
        throw err
      }
      finally {
        loading.value.ownerFreightPage = false
      }
    }

    /**
     * 获取部门下用户列表
     */
    async function fetchDepartUserList(data: {
      pageSize: number
      pageNo: number
      departId?: string
    }, forceRefresh = false) {
      // 如果已有数据且不强制刷新，则直接返回
      if (departUserList.value.length > 0 && !forceRefresh) {
        return departUserList.value
      }

      try {
        loading.value.departUserList = true
        error.value.departUserList = ''
        const res = await getDepartUserList(data)

        // 确保返回结果是数组
        if (Array.isArray(res.data.records)) {
          departUserList.value = res.data.records
        }
        else {
          console.warn('API 返回的部门下用户列表不是数组，当前值:', res)
          departUserList.value = []
        }

        return departUserList.value
      }
      catch (err: any) {
        error.value.departUserList = err.message || '获取部门下用户列表失败'
        // 发生错误时设置为空数组
        departUserList.value = []
        throw err
      }
      finally {
        loading.value.departUserList = false
      }
    }

    /**
     * 清除所有缓存数据
     */
    function clearAll() {
      tenantDepartTree.value = null
      logisticsPayTypeDict.value = []
      paymentTypeDict.value = []
      invoiceTypeDict.value = []
      logisticsFreightTypeDict.value = []
      bpmTaskStatusDict.value = []
      companyList.value = []
      employeeList.value = []
      departUserList.value = []
      ownerFreightPage.value = null
      loading.value = {}
      error.value = {}
    }

    /**
     * 清除特定数据
     */
    function clearData(key: string) {
      switch (key) {
        case 'tenantDepartTree':
          tenantDepartTree.value = null
          break
        case 'logisticsPayTypeDict':
          logisticsPayTypeDict.value = []
          break
        case 'paymentTypeDict':
          paymentTypeDict.value = []
          break
        case 'invoiceTypeDict':
          invoiceTypeDict.value = []
          break
        case 'logisticsFreightTypeDict':
          logisticsFreightTypeDict.value = []
          break
        case 'bpmTaskStatusDict':
          bpmTaskStatusDict.value = []
          break
        case 'companyList':
          companyList.value = []
          break
        case 'employeeList':
          employeeList.value = []
          break
        case 'ownerFreightPage':
          ownerFreightPage.value = null
          break
        case 'departUserList':
          departUserList.value = []
          break
      }
      // 清除对应的加载状态和错误信息
      delete loading.value[key]
      delete error.value[key]
    }

    return {
      // 状态数据
      tenantDepartTree,
      logisticsPayTypeDict,
      paymentTypeDict,
      invoiceTypeDict,
      logisticsFreightTypeDict,
      bpmTaskStatusDict,
      companyList,
      employeeList,
      ownerFreightPage,
      loading,
      error,

      // 计算属性
      defaultCompany,
      getCompanyById,
      getEmployeeById,
      getSelectUserList,

      // 方法
      fetchUserTenantDepartTree,
      fetchLogisticsPayTypeDict,
      fetchInvoiceTypeDict,
      fetchLogisticsFreightTypeDict,
      fetchBpmTaskStatusDict,
      fetchCompanyList,
      fetchEmployeeList,
      fetchOwnerFreightPage,
      fetchDepartUserList,
      fetchPaymentTypeDict,
      clearAll,
      clearData,
    }
  },
  {
    persist: true,
  },
)
